import React, { PureComponent, useRef } from 'react';
import Taro from '@tarojs/taro'
import { Component } from 'react'
import { View, Image, Text, Button } from '@tarojs/components'
import { SpNavBar } from '@/components'
import { AtListItem } from 'taro-ui'
import { CapsuleTabs, Grid, CalendarPicker, List, InfiniteScroll, CheckList, Popup } from "antd-mobile";
import './index.scss'
import dayjs from 'dayjs';
import api from '@/api';
import merchant from '@/store/slices/merchant';

const jyList = [{
    title: '订单数',
    key: 'order_count',
    isDeci: false
}, {
    title: '付款订单数',
    key: 'order_payed_count',
    isDeci: false
}, {
    title: '交易额(元)',
    key: 'amount_payed_count',
    isDeci: true
}, {
    title: 'GMV(元)',
    key: 'gmv_count',
    isDeci: true
}, {
    title: '售后订单数',
    key: 'aftersales_count',
    isDeci: false
}, {
    title: '退款额(元)',
    key: 'refunded_count',
    isDeci: true
}]
const defaultMerchant = { distributor_id: 'all', name: '全部' }
class StatusRecord extends Component {
    constructor(props) {
        super(props);
    }
    state = {
        timevisible1: false,
        timevisible2: false,
        timevisible3: false,
        timevisible4: false,
        popVisible: false,
        threeMonthsAgo: '',
        timeType: '',
        merchantList: [{ distributor_id: 'all', name: '全部' }],
        normolMerchant: { distributor_id: 'all', name: '全部' },
        calendarDate: {
            jy: [],
            dp: [],
            sp: []
        },
        jyData: {},
        dpData: {},
        spData: [],
    }
    async componentDidMount() {
        var currentTime = new Date();
        // 7天的毫秒数
        var sevenDays = 7 * 24 * 60 * 60 * 1000;
        // 7天前的毫秒数
        var sevenDaysAgo = currentTime - sevenDays;
        // 7天前的日期
        let sevenDaysAgoDate = dayjs(sevenDaysAgo).format('YYYY-MM-DD')
        let nowDate = dayjs().subtract(1, 'day').format('YYYY-MM-DD')
        let threeMonthsAgo = new Date(currentTime.setMonth(currentTime.getMonth() - 3)).getTime();
        const time = {
            jy: [sevenDaysAgoDate, nowDate],
            dp: [sevenDaysAgoDate, nowDate],
            sp: [sevenDaysAgoDate, nowDate]
        }
     this.setState({
            calendarDate: time,
            threeMonthsAgo: threeMonthsAgo
        })
        this.getCompanydata()
        this.getDistributordata()
        this.getGoodsdata()
        this.getMerchantList()
        // formRef = React.createRef()
        // const ref1 = useRef(null)
        // const ref2 = useRef(null)
    }
    async getCompanydata() {
        const { calendarDate, jyData, dpData, spData } = this.state
        console.log(calendarDate.jy[0])
        const source = await api.my.getCompanydata({
            start: calendarDate.jy[0],
            end: calendarDate.jy[calendarDate.jy.length - 1]
        })
        const data = source.list
        let jyDataSource = {
            order_count: data.reduce(function (acc, obj) {
                return acc + obj.order_count
            }, 0),
            order_payed_count: data.reduce(function (acc, obj) {
                return acc + obj.order_payed_count
            }, 0),
            amount_payed_count: data.reduce(function (acc, obj) {
                return acc + parseInt(obj.amount_payed_count)
            }, 0),
            gmv_count: data.reduce(function (acc, obj) {
                return acc + parseInt(obj.gmv_count)
            }, 0),
            aftersales_count: data.reduce(function (acc, obj) {
                return acc + obj.aftersales_count
            }, 0),
            refunded_count: data.reduce(function (acc, obj) {
                return acc + obj.refunded_count
            }, 0)
        }
        this.setState({
            jyData: jyDataSource
        })

    }
    async getMerchantList() {
        const data = await api.shop.getShopList({
            is_valid: true,
            pageSize:1000
        })
        console.log(data)
        this.setState({
            merchantList: [defaultMerchant, ...data.list]
        })
    }
    async getGoodsdata() {
        const query = {
            start: this.state.calendarDate.sp[0],
            end: this.state.calendarDate.sp[1]
        }
        // if (this.listIndex === 0) {
        //     query.quantity = 'desc'
        // } else if (this.listIndex === 1) {
        //     query.fix_price = 'desc'
        // } else if (this.listIndex === 2) {
        //     query.settle_price = 'desc'
        // }
        let source = await api.my.getGoodsdata(query)

        // list = list.splice(list.length - 1, 1)

        console.log(source)
        this.setState({
            spData: source.list
        })
        // this.spData.splice(this.spData.length - 1, 1)
    }
    async getDistributordata() {
        let source = await api.my.getDistributordata({
            start: this.state.calendarDate.dp[0],
            end: this.state.calendarDate.dp[1],
            distributor_id: this.state.normolMerchant.distributor_id
        })
        const data = source.list
        let dpDataDource = {
            order_count: data.reduce(function (acc, obj) {
                return acc + parseInt(obj.order_count)
            }, 0),
            order_payed_count: data.reduce(function (acc, obj) {
                return acc + parseInt(obj.order_payed_count)
            }, 0),
            amount_payed_count: data.reduce(function (acc, obj) {
                return acc + parseInt(obj.amount_payed_count)
            }, 0),
            gmv_count: data.reduce(function (acc, obj) {
                return acc + parseInt(obj.gmv_count)
            }, 0),
            aftersales_count: data.reduce(function (acc, obj) {
                return acc + parseInt(obj.aftersales_count)
            }, 0),
            refunded_count: data.reduce(function (acc, obj) {
                return acc + parseInt(obj.refunded_count)
            }, 0)
        }
        this.setState({
            dpData: dpDataDource
        })
    }
    formatA(num) {
        var result = parseFloat(num)
        if (isNaN(result)) {
            console.log('传递参数错误，请检查！')
            return false
        }
        result = Math.round(num * 100) / 100
        var s_x = result.toString()
        var pos_decimal = s_x.indexOf('.')
        if (pos_decimal < 0) {
            pos_decimal = s_x.length
            s_x += '.'
        }
        while (s_x.length <= pos_decimal + 2) {
            s_x += '0'
        }
        return s_x
    }
    render() {
        const { calendarDate, jyData, dpData, spData } = this.state
        return (
            <View>
                <SpNavBar title='数据分析'></SpNavBar>
                <View className='status-record'>
                    <CapsuleTabs onChange={(key) => {
                        console.log(key)
                    }}>
                        <CapsuleTabs.Tab title='交易' key='1'>
                            <View className='jaoyi-status-record-head'>
                                <AtListItem title='交易统计' arrow='right' onClick={() => {
                                    // this.ref1.current?.jumpToToday()
                                    this.setState({
                                        timeType: 1,
                                        timevisible1: true
                                    })

                                }} extraText={`${calendarDate.jy[0]}至${calendarDate.jy[calendarDate.jy.length - 1]}`} />
                            </View>
                            <Grid columns={3} gap={8} className='status-record-grid'>
                                {jyList.map((value, index) => {
                                    return (
                                        <Grid.Item  key={index+100}>
                                            <View >
                                                <View className="status-record-grid-title" style="text-align: center;">{value.title}</View>
                                                <View className="status-record-grid-label" style="text-align: center;">{(!value.isDeci) ? jyData[value.key] : this.formatA(jyData[value.key] / 100)}</View>
                                            </View>

                                        </Grid.Item>
                                    )
                                })}
                            </Grid>
                            <CalendarPicker
                                visible={this.state.timevisible1}
                                defaultValue={this.state.calendarDate.jy}
                                selectionMode='range'
                                onClose={() => {
                                    this.setState({
                                        timevisible1: false
                                    })
                                }}
                                min={this.state.threeMonthsAgo}
                                max={dayjs().subtract(1, 'day').toDate()}
                                onConfirm={val => {
                                    let time = this.state.calendarDate
                                    time.jy = [dayjs(val[0]).format('YYYY-MM-DD'), dayjs(val[1]).format('YYYY-MM-DD')]
                                    this.setState({
                                        calendarDate: time
                                    })
                                    this.getCompanydata()
                                }}
                            />
                        </CapsuleTabs.Tab>
                        <CapsuleTabs.Tab title='店铺' key='2'>
                            <View className='dianpu-status-record-head'>
                                <View className='title'><View className='title-text'>交易统计</View></View>
                                <View className='rigth' >
                                    <AtListItem arrow='right' extraText={this.state.normolMerchant.name} onClick={() => {
                                        this.setState({
                                            popVisible: true
                                        })
                                    }} />

                                    <AtListItem arrow='right' onClick={() => {
                                        this.setState({
                                            timeType: 2,
                                            timevisible2: true
                                        })
                                    }} extraText={`${calendarDate.dp[0]}至${calendarDate.dp[calendarDate.dp.length - 1]}`} />
                                </View>

                            </View>
                            <Grid columns={3} gap={8} className='status-record-grid'>
                                {jyList.map((value, index) => {
                                    return (
                                        <Grid.Item key={value.key}>
                                            <View   >
                                                <View className="status-record-grid-title" style="text-align: center;">{value.title}</View>
                                                <View className="status-record-grid-label" style="text-align: center;">{(!value.isDeci) ? dpData[value.key] : this.formatA(dpData[value.key] / 100)}</View>

                                            </View>

                                        </Grid.Item>
                                    )
                                })}
                            </Grid>
                            <CalendarPicker
                                visible={this.state.timevisible2}
                                defaultValue={this.state.calendarDate.dp}
                                selectionMode='range'
                                onClose={() => {
                                    this.setState({
                                        timevisible2: false
                                    })

                                }}
                                min={this.state.threeMonthsAgo}
                                max={dayjs().subtract(1, 'day').toDate()}
                                onConfirm={val => {
                                    let time = this.state.calendarDate
                                    time.dp = [dayjs(val[0]).format('YYYY-MM-DD'), dayjs(val[1]).format('YYYY-MM-DD')]
                                    this.setState({
                                        calendarDate: time
                                    })
                                    this.getDistributordata()
                                }}
                            />
                        </CapsuleTabs.Tab>
                        <CapsuleTabs.Tab title='商品' key='3'>
                            <View className='status-record-head'>
                                <AtListItem title='商品统计' onClick={() => {
                                    this.setState({
                                        timeType: 3,
                                        timevisible3: true
                                    })
                                }} arrow='right' extraText={`${calendarDate.sp[0]}至${calendarDate.sp[calendarDate.sp.length - 1]}`} />
                            </View>
                            <List>

                                {!!spData.length && spData.map((item, index) => {
                                    if (index == (spData.length - 1)) {
                                        return (<List.Item key='234w3r'>
                                            <View className='totle-view'>
                                                <View style="color:red">
                                                    总计:
                                                </View>
                                                <View>
                                                    销量:{item.quantity}
                                                </View>
                                                <View>
                                                    销售额:{item.fix_price}
                                                </View>
                                                <View>
                                                    实付额:{item.settle_price}
                                                </View>
                                            </View>
                                        </List.Item>)
                                    } else
                                        return (<List.Item key={item.sap_code} >
                                            <View  className='status-record-comp-item'>
                                                <View className='status-record-comp-item-good'>
                                                    <View className='status-record-comp-item-good-pic'>
                                                        <Image className='img' src={item.pics.length > 0 ? item.pics[0] : ''} />
                                                    </View>
                                                    <View className='status-record-comp-item-good-center'>
                                                        <View className='good-name'>{item.product}</View>
                                                        <View className='good-no'>货号：{item.sap_code}</View>
                                                    </View>
                                                    <View className='status-record-comp-item-good-right'>
                                                        <View className='sale_price'>
                                                            <View className='sale_price_label'>销售额:</View>
                                                            <View className='sale_price_label'>{item.fix_price}</View>
                                                        </View>
                                                        <View className='sale_price'>
                                                            <View className='sale_price_label'>实付额:</View>
                                                            <View className='sale_price_label'>{item.settle_price}</View>
                                                        </View>
                                                        <View className='sale_store'>
                                                            <View className='sale_store_label'>销量</View>
                                                            <View className='sale_store_number'>{item.quantity}</View>
                                                        </View>
                                                    </View>
                                                </View>
                                            </View>
                                        </List.Item>)
                                })}
                            </List>
                            <CalendarPicker
                                visible={this.state.timevisible3}
                                defaultValue={this.state.timeType == 1 ? this.state.calendarDate.jy : (this.state.timeType == 2 ? this.state.calendarDate.dp : this.state.calendarDate.sp)}
                                selectionMode='range'
                                min={this.state.threeMonthsAgo}
                                max={dayjs().subtract(1, 'day').toDate()}
                                onClose={() => {
                                    this.setState({
                                        timevisible3: false
                                    })
                                }}

                                onMaskClick={() => {
                                    this.setState({
                                        timevisible3: false
                                    })
                                }}
                                onChange={val => {
                                    console.log(val)
                                }}
                                onConfirm={val => {
                                    let time = this.state.calendarDate

                                    time.sp = [dayjs(val[0]).format('YYYY-MM-DD'), dayjs(val[1]).format('YYYY-MM-DD')]

                                    this.setState({
                                        calendarDate: time
                                    })
                                    this.getGoodsdata()
                                }}
                            />
                        </CapsuleTabs.Tab>
                        <CapsuleTabs.Tab title='结算' key='4' >

                        </CapsuleTabs.Tab>
                    </CapsuleTabs>
                </View>

                <Popup
                className='status-popup'
                    visible={this.state.popVisible}
                    onMaskClick={() => {
                        this.setState({ popVisible: false })
                    }}
                    destroyOnClose
                >
                    <div>
                        <CheckList
                            className='status-popup-checkList'
                            defaultValue={[this.state.normolMerchant.distributor_id]}
                            onChange={async(val) => {
                                console.log(val)
                                // setSelected(val[0])
                                if (val.length <= 0) {
                                    val[0] = 'all'
                                }
                                let arr = this.state.merchantList.filter((item) => {
                                    return item.distributor_id == val[0]
                                })
                                console.log(arr[0])
                                 this.setState({
                                    normolMerchant: arr[0],
                                    popVisible: false
                                },()=>{
                                    this.getDistributordata()
                                })
                                

                            }}
                        >

                            {this.state.merchantList.map(item => (
                                <CheckList.Item key={item.distributor_id} value={item.distributor_id}>
                                    {item.name}
                                </CheckList.Item>
                            ))}
                        </CheckList>
                    </div>
                </Popup>
            </View>
        );
    }
}

export default StatusRecord;